package code {

import code.vo.Category;
import code.vo.NeededTopic;
import code.vo.User;

import com.adobe.cairngorm.model.IModelLocator;

import mx.collections.ArrayCollection;
import mx.controls.AdvancedDataGrid;
	

[Bindable]
public class Model implements IModelLocator {

	public var loginUsername: String;
	public var loginPassword: String;
	public var loginEmail: String;
	
	public var loginRemember: Boolean;
	public var isLoginBlocked: Boolean = false;
	
	
	public var currentUser: User;
	
	public var neededCategories: ArrayCollection = new ArrayCollection();
	
	public var offeredTopics: ArrayCollection = new ArrayCollection();

	public var neededTopicsAdvancedDataGridHack: AdvancedDataGrid;


	private static var INSTANCE: Model; 
	public function Model(singletonEnforcer: SingletonEnforcer) { }
	public static function get instance(): Model {
		if(INSTANCE == null) { INSTANCE = new Model(new SingletonEnforcer()); }
		return INSTANCE;
	}
	
	private var neededCategoriesMapping: Array = null;
	private function initializeNeededCategoriesMapping(): void {
		if(this.neededCategories == null) {
			throw new Error("Illegal state: neededCategories == null");
		}
		if(this.neededCategoriesMapping != null) {
			throw new Error("Illegal state: neededCategoriesMapping != null");
		}
		
		this.neededCategoriesMapping = new Array();
		for each(var cat: Category in this.neededCategories) {
			this.neededCategoriesMapping[cat.categoryId] = cat;
		}
	}
	
	public function addNeededTopicByCategory(topic: NeededTopic): void {
		if(this.neededCategoriesMapping == null) {
			this.initializeNeededCategoriesMapping();
		}
		
		const c: Category = this.neededCategoriesMapping[topic.categoryId] as Category;
		c.topics.addItem(topic);
	}
	
	public function getCategoryById(id: int): Category {
		const result: Category = this.neededCategoriesMapping[id];
		if(result == null) {
			throw new Error("Invalid category id: " + id);
		}
		return result;
	}
	
	
	
	private var _usersMapping: Array = null;
	public function setUsers(users: ArrayCollection): void {
		/* TODO register request needs to rewrite this stuff ... if(_usersMapping != null) {
			throw new Error("Users mapping already set!");
		}*/
		_usersMapping = new Array();
		for each(var u: User in users) {
			_usersMapping[u.userId] = u;
		}
	}
	
	public function getUserById(id: int): User {
		const result: User = _usersMapping[id];
		if(result == null) {
			throw new Error("Invalid user id: " + id);
		}
		return result;
	}
}
}

class SingletonEnforcer { }
